import * as React from 'react';
import { Tree , Button, Modal, Form, Input, Segmented} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import './tableTree.scss'
import Item from 'antd/es/list/Item';

const { TreeNode } = Tree;

const TreeStyle ={
    height : "689px",
    'background-color' : "whitesmoke"
    
}

const userId = 1;

//fetch


const initDataaaa = [
 { "title": "test",
  "name": "test",
  "key": "0-0",
  "children": [
      {
          "title": "生产商",
          "name": "producer",
          "key": "3",
          "children": []
      },
      {
          "title": "商品",
          "name": "goods",
          "key": "4",
          "children": []
      },
      {
          "title": "订单",
          "name": "order",
          "key": "8",
          "children": [
              {
                  "title": "订单明细",
                  "name": "order_item",
                  "key": "9",
                  "children": []
              }
          ]
      }
  ]}
]

interface Entity{
  name? :string;
  displayName?: string;
  type?: string;
}



const TableTree = ({onNodeSelect}) => {
  let initData = [];
  
 const appId = localStorage.getItem('appId');


  const [treeData, setTreeData] = React.useState(initData);
  const [form] = Form.useForm();
  const [selectItem, setSelectItem] = React.useState();
  const [formValues, setFormValues] = React.useState<Entity>({name:"",displayName:"",type:''});
  const [open, setOpen] = React.useState(false);

  React.useEffect(() =>{
        fetch('http://localhost:8080/api/v1/entity/tree?appId='+appId)
    .then(response => response.json())
    .then(data => {setTreeData([data.data]); });
  },[])

  let aaavalues:Entity;
  React.useEffect(()=>{
    console.log(formValues);
    aaavalues = formValues;
    console.log("aaavalues:",aaavalues);
  },[formValues])

  const addNode = (parentNodeKey,values) => {
    return () => {
      setTreeData((origin) => {
        // 打印原始数据（更新前）
        console.log('Before update:', JSON.stringify(origin));
       
        console.log("abc",values);
        // 使用时间戳和随机数生成唯一的key
        const newChildKey = `${parentNodeKey}-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
        const newChild = { title: values.displayName , name:values.name, key: newChildKey, children: [] };

        const updateNodes = (nodes) => nodes.map((node) => {
          if (node.key === parentNodeKey) {
            return {
              ...node,
              children: node.children ? [...node.children, newChild] : [newChild],
            };
          }
          if (node.children) {
            return { ...node, children: updateNodes(node.children) };
          }
          return node;
        });

        // 更新后的数据
        const updatedData = updateNodes(origin);
        // 打印更新后的数据
        console.log('After update:', JSON.stringify(updatedData));

        return updatedData;
      });
    };
  };

  const handleNodeSelect = (selectedKeys, info) => {
    console.log(info.node);
    onNodeSelect(info.node.dataRef.name); // 或者根据你的需求调整参数
  };
 

  const handleClickTreeNode = (item) => {
    setOpen(true);
    //console.log(item.key);
    //console.log(item.key === "0-0" ? 'PLAIN' : 'CHILD');
    setSelectItem(item);
    setFormValues({...formValues,type: item.key === "0-0" ? 'PLAIN' : 'CHILD'});
    console.log({...formValues,type: item.key === "0-0" ? 'PLAIN' : 'CHILD'});
  }
 
  const renderTreeNodes = (data) =>
    data.map((item) => (
      <TreeNode style={{width: '100%'}} autoExpandParent={true} title={
        <>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span>{item.title}</span>
          {/* <Button shape="circle" size="small" type="primary" icon={<PlusOutlined />} onClick={addNode(item.key)}></Button> */}
          <PlusOutlined onClick={() => {handleClickTreeNode(item)}} className={'addIcon'}/>
          </div>
        </>
      } key={item.key} dataRef={item}>
        {item.children && renderTreeNodes(item.children)}
      </TreeNode>
    ));



  const handleSubmitEntity = (values) => {
    onCreate(values);
    console.log(selectItem);
    addNode(selectItem.key,values)();
    fetch('http://localhost:8080/api/v1/entity/lc?appId='+appId+'&userId='+userId,{
      method: 'POST', 
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(
        {...formValues,...values, parent: selectItem.name}
      )
  }).then(response => response.json())
  .then(data => {console.log(data)})
  }
  

  const onCreate = (entity: Entity) => {
    
    setFormValues({...formValues,...entity,});
    console.log('Received values of form: ', {...formValues,...entity,});
    setOpen(false);
    
  };

    const EntityModal:React.FC = () => {
      return (
        <Modal
        open={open}
        title="创建实体"
        okText="提交"
        cancelText="取消"
        okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
        onCancel={() => setOpen(false)}
        destroyOnClose
        modalRender={(dom) => (
          <Form
            layout="vertical"
            form={form}
            name="form_in_modal"
            clearOnDestroy
            onFinish={(values) => handleSubmitEntity(values)}
          >
            {dom}
          </Form>
        )}
        >
          <Form.Item
          name="name"
          label="名称"
          rules={[{ required: true, message: 'Please input the name of table!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="displayName"
          label="中文名称"
          rules={[{ required: true, message: 'Please input the displayName of table!' }]}
        >
          <Input />
        </Form.Item>
        
        </Modal>
      )
    }

  return (
    
    <>
    
      <Tree defaultExpandAll={true} style={TreeStyle} onSelect={handleNodeSelect}>
        {renderTreeNodes(treeData)}
      </Tree>
      <EntityModal/>
      {/* <Modal open={true}>{'aaa'}</Modal> */}
    </>
  );
};

export default TableTree;